﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

namespace Enterprise.Management.Common
{
    public static class Extension
    {
        public static string ToSQLString(this string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;

            return value.Replace("'", "''").Replace("--", "");
        }

        public static string ToSQLLikeString(this string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;

            return value.Replace("[", "[[]").Replace("%", "[%]").Replace("_", "[_]").Replace("^", "[^]");
        }

        public static string ToSafeTrim(this string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;

            return value.Trim();
        }

        public static string ToSafeString(this object value)
        {
            if (value == null) return string.Empty;

            return value.ToString();
        }

        public static string ToHtmlString(this string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;

            return HttpUtility.HtmlEncode(value);
        }

        public static string ToBase64(this string value)
        {
            byte[] bytes = Encoding.Default.GetBytes(value);
            return Convert.ToBase64String(bytes);
        }

        public static string FromBase64(this string value)
        {
            byte[] bytes = Convert.FromBase64String(value);
            return Encoding.Default.GetString(bytes);
        }

        public static int ToSafeInt32(this object value, int defaultValue = 0)
        {
            if (value == null) return defaultValue;

            int retValue;
            if (!int.TryParse(value.ToString(), out retValue))
            {
                retValue = defaultValue;
            }

            return retValue;
        }

        public static bool HasFile(this HttpPostedFileBase file)
        {
            return (file != null && file.ContentLength > 0) ? true : false;
        }
    }
}